package com.wanxi.config.handler;

import com.alibaba.fastjson.JSON;
import com.wanxi.dto.ResultDto;
import com.wanxi.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Li
 * @Date 2023/7/15 10:39
 */
@Component
public class AuthenticationEntityPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//       认证失败处理
//        HttpStatus.UNAUTHORIZED.value()调用http中的异常处理信息，这里需要参数类型为Integer，使用.value()转换
        ResultDto resultDto = new ResultDto(HttpStatus.UNAUTHORIZED.value(), "用户认证失败请先登录");
//        转换成JSON的字符串
        String jsonString = JSON.toJSONString(resultDto);
        WebUtils.renderString(response, jsonString);
    }
}
